package com.shanwen.shopping.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.classic.core.log.Logger;
import com.shanwen.shopping.R;
import com.shanwen.shopping.adapter.CategoryAdapter;
import com.shanwen.shopping.adapter.DialogListAdapter;
import com.shanwen.shopping.adapter.NewGoodsAdapter;
import com.shanwen.shopping.entity.GoodsClassify;
import com.shanwen.shopping.entity.GoodsInfo;
import com.shanwen.shopping.http.ActionHelp;
import com.shanwen.shopping.http.ListCallback;
import com.shanwen.shopping.pop.EasyPopup;
import com.shanwen.shopping.pop.HorizontalGravity;
import com.shanwen.shopping.pop.VerticalGravity;
import com.shanwen.shopping.utils.GoodsDaoUtil;
import com.shanwen.shopping.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

/**
 * Created by lex on 2017/9/27.
 */

public class GoodsActivity extends AppBaseActivity {

    @BindView(R.id.common_titlebar_layout)
    LinearLayout commonTitlebarLayout;
    @BindView(R.id.lvCategory)
    ListView lvCategory;
    @BindView(R.id.lvList)
    ListView lvList;
    @BindView(R.id.tvConfirmPrice)
    TextView tvConfirmPrice;
    @BindView(R.id.btnConfirm)
    Button btnConfirm;
    @BindView(R.id.rlCartIcon)
    RelativeLayout rlCartIcon;
    @BindView(R.id.llConfirmBottom)
    LinearLayout llConfirmBottom;

    private List<GoodsClassify> categoryList;
    private List<GoodsInfo> goodsInfoList;
    private CategoryAdapter categoryAdapter;
    private QBadgeView badgeView;
    private NewGoodsAdapter newGoodsAdapter;
    private long curItemId = -1;

    private GoodsDaoUtil goodsDaoUtil;
    private EasyPopup easyPopup;

    private ListView lvDialog;
    private TextView tvCleanCart;
    private LinearLayout mComplexBgDimView;
    private DialogListAdapter dialogListAdapter;
    private PopupWindow popupWindow;
    private Badge badge;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_goods;
    }


    @Override
    public void initView() {
        super.initView();
        setTitle("商城");
        setBackEnabled(true);
        goodsDaoUtil = new GoodsDaoUtil(this);
        categoryList = new ArrayList<>();
        goodsInfoList = new ArrayList<>();
        categoryAdapter = new CategoryAdapter(activity, categoryList);
        newGoodsAdapter = new NewGoodsAdapter(activity, goodsInfoList);
        lvCategory.setAdapter(categoryAdapter);
        lvList.setEmptyView(findViewById(R.id.emptyView));
        lvList.setAdapter(newGoodsAdapter);
        lvCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                curItemId = categoryList.get(position).getItemId();
                for (int i = 0; i < categoryList.size(); i++) {
                    if (i == position) {
                        categoryList.get(i).setSelected(true);
                    } else {
                        categoryList.get(i).setSelected(false);
                    }
                    categoryAdapter.notifyDataSetChanged();
                }
                getGoodsByClassifyId(curItemId);
            }
        });

        newGoodsAdapter.setOnNumClickListener(new NewGoodsAdapter.NumClickListener() {
            @Override
            public void jia(GoodsInfo goodsInfo) {
                goodsInfo.setNum(goodsInfo.getNum() + 1);
                GoodsInfo goodsInfo1 = goodsDaoUtil.queryGoodsInfoById(goodsInfo.getGoodsId());
                if (null == goodsInfo1) {
                    goodsDaoUtil.insertGoodsInfo(goodsInfo);
                } else {
                    goodsDaoUtil.updateGoodsInfoField(goodsInfo1, goodsInfo.getNum());
                }
                List<GoodsInfo> list = goodsDaoUtil.queryAllGoodsInfoByQueryBuilder();
                long price = 0L;
                int allNum = 0;
                for (int i = 0; i < list.size(); i++) {
                    price += list.get(i).getSalePrice() * list.get(i).getNum();
                    allNum += list.get(i).getNum();
                }
                badge.setBadgeNumber(allNum);
                tvConfirmPrice.setText(Utils.formatPrice(price));
                newGoodsAdapter.notifyDataSetChanged();
            }

            @Override
            public void jian(GoodsInfo goodsInfo) {
                if (goodsInfo.getNum() >= 1) {
                    if (goodsInfo.getNum() > 1) {
                        goodsInfo.setNum(goodsInfo.getNum() - 1);
                        goodsDaoUtil.updateGoodsInfoField(goodsInfo, goodsInfo.getNum());
                    } else {
                        goodsInfo.setNum(goodsInfo.getNum() - 1);
                        goodsDaoUtil.deleteGoodsInfo(goodsInfo);
                    }
                }
                List<GoodsInfo> list = goodsDaoUtil.queryAllGoodsInfoByQueryBuilder();
                long price = 0L;
                int allNum = 0;
                for (int i = 0; i < list.size(); i++) {
                    price += list.get(i).getSalePrice() * list.get(i).getNum();
                    allNum += list.get(i).getNum();
                }
                badge.setBadgeNumber(allNum);
                tvConfirmPrice.setText(Utils.formatPrice(price));
                newGoodsAdapter.notifyDataSetChanged();
            }
        });
        getClassifyList();
        mComplexBgDimView = (LinearLayout) findViewById(R.id.ll_complex_bg_dim);
        easyPopup = new EasyPopup(this);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        View v = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);
        easyPopup.setContentView(v, ViewGroup.LayoutParams.MATCH_PARENT, height / 2);
        easyPopup.setDimView(mComplexBgDimView).createPopup();
        easyPopup.setFocusAndOutsideEnable(false)
                .setBackgroundDimEnable(true)
                .setDimValue(0.6f);
        popupWindow = easyPopup.getPopupWindow();
        popupWindow.setFocusable(false);
        lvDialog = (ListView) v.findViewById(R.id.lvDialog);
        tvCleanCart = (TextView) v.findViewById(R.id.tvCleanCart);

        //清空购物车按钮
        tvCleanCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<GoodsInfo> dataList = newGoodsAdapter.getDataList();
                for (int i = 0; i < dataList.size(); i++) {
                    dataList.get(i).setNum(0);
                }
                newGoodsAdapter.notifyData(dataList);
                badge.setBadgeNumber(0);
                rlCartIcon.setBackgroundResource(R.drawable.shape_circle);
                mComplexBgDimView.setVisibility(View.GONE);
                goodsDaoUtil.deleteAll();
                popupWindow.dismiss();
                tvConfirmPrice.setText(Utils.formatPrice(0l));
            }
        });
        mComplexBgDimView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mComplexBgDimView.setVisibility(View.GONE);
                rlCartIcon.setBackgroundResource(R.drawable.shape_circle);
                popupWindow.dismiss();
            }
        });
        rlCartIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow.isShowing()) {
                    mComplexBgDimView.setVisibility(View.GONE);
                    popupWindow.dismiss();
                    rlCartIcon.setBackgroundResource(R.drawable.shape_circle);
                } else {
                    mComplexBgDimView.setVisibility(View.VISIBLE);
                    List<GoodsInfo> list = goodsDaoUtil.queryAllGoodsInfoByQueryBuilder();
                    if (list.size() == 0) {
                        Toast.makeText(GoodsActivity.this, "还没有添加商品", Toast.LENGTH_SHORT).show();
                        mComplexBgDimView.setVisibility(View.GONE);
                        return;
                    }
                    rlCartIcon.setBackgroundResource(R.drawable.shape_circle2);
                    if (null == dialogListAdapter) {
                        dialogListAdapter = new DialogListAdapter(GoodsActivity.this, list);
                        lvDialog.setAdapter(dialogListAdapter);
                    } else {
                        dialogListAdapter.notifyData(list);
                    }
                    dialogListAdapter.setOnNumClickListener(new DialogListAdapter.NumClickListener() {
                        @Override
                        public void jia(GoodsInfo goodsInfo) {
                            goodsInfo.setNum(goodsInfo.getNum() + 1);
                            List<GoodsInfo> list = goodsDaoUtil.queryAllGoodsInfoByQueryBuilder();
                            long price = 0L;
                            int allNum = 0;
                            for (int i = 0; i < list.size(); i++) {
                                price += list.get(i).getSalePrice() * list.get(i).getNum();
                                allNum += list.get(i).getNum();
                            }
                            badge.setBadgeNumber(allNum);
                            tvConfirmPrice.setText(Utils.formatPrice(price));
                            dialogListAdapter.notifyData(list);
                            List<GoodsInfo> list_all = newGoodsAdapter.getDataList();
                            for (int i = 0; i < list_all.size(); i++) {
                                if (list_all.get(i).getGoodsId() == goodsInfo.getGoodsId()) {
                                    list_all.get(i).setNum(goodsInfo.getNum());
                                }
                            }
                            newGoodsAdapter.notifyData(list_all);
                        }

                        @Override
                        public void jian(GoodsInfo goodsInfo) {
                            if (goodsInfo.getNum() >= 1) {
                                if (goodsInfo.getNum() > 1) {
                                    goodsInfo.setNum(goodsInfo.getNum() - 1);
                                    goodsDaoUtil.updateGoodsInfoField(goodsInfo, goodsInfo.getNum());
                                } else {
                                    goodsInfo.setNum(0);
                                    goodsDaoUtil.deleteGoodsInfo(goodsInfo);
                                }
                            }
                            List<GoodsInfo> list = goodsDaoUtil.queryAllGoodsInfoByQueryBuilder();
                            long price = 0L;
                            int allNum = 0;
                            for (int i = 0; i < list.size(); i++) {
                                price += list.get(i).getSalePrice() * list.get(i).getNum();
                                allNum += list.get(i).getNum();
                            }
                            badge.setBadgeNumber(allNum);
                            tvConfirmPrice.setText(Utils.formatPrice(price));
                            dialogListAdapter.notifyData(list);

                            List<GoodsInfo> list_all = newGoodsAdapter.getDataList();
                            for (int i = 0; i < list_all.size(); i++) {
                                if (list_all.get(i).getGoodsId() == goodsInfo.getGoodsId()) {
                                    list_all.get(i).setNum(goodsInfo.getNum());
                                }
                            }
                            newGoodsAdapter.notifyData(list_all);
                        }
                    });
                    showComplexPop(llConfirmBottom);
                }
            }
        });

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goodsDaoUtil.queryAllGoodsInfoByQueryBuilder().size() == 0) {
                    Toast.makeText(GoodsActivity.this, "还没有添加商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(GoodsActivity.this, OrderCommitActivity.class);
                startActivity(intent);
            }
        });
    }

    private void showComplexPop(View view) {
        easyPopup.showAtAnchorView(view, VerticalGravity.ABOVE, HorizontalGravity.LEFT, 0, -96);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        badgeView = new QBadgeView(activity);
        badgeView.setBadgeTextSize(30, true);
        badge = badgeView.bindTarget(rlCartIcon);
    }


    private void getClassifyList() {
        ActionHelp.qryGoodsItems(activity,
                new ListCallback<GoodsClassify>() {
                    @Override
                    public void onSuccess(List<GoodsClassify> response) {
                        Logger.d("获取分类成功:" + response.toString());
                        mComplexBgDimView.setVisibility(View.GONE);
                        if (null == response) {
                            return;
                        } else {
                            categoryList.clear();
                            categoryList.addAll(response);
                            categoryList.get(0).setSelected(true);
                            categoryAdapter.notifyDataSetChanged();
                            getGoodsByClassifyId(categoryList.get(0).getItemId());
                        }
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        super.onError(code, errorMessage);
                        Logger.e("获取分类失败:" + code + "," + errorMessage);
                    }

                    @Override
                    public Class<GoodsClassify> getType() {
                        return GoodsClassify.class;
                    }
                }
        );
    }


    private void getGoodsByClassifyId(long classifyId) {
        ActionHelp.qryGoodsByItemId(activity, classifyId + "",
                new ListCallback<GoodsInfo>() {
                    @Override
                    public void onSuccess(List<GoodsInfo> response) {
                        Logger.d("获取商品列表成功:" + response.toString());
                        List<GoodsInfo> sqlData = goodsDaoUtil.queryAllGoodsInfo();
                        if (null == response) {
                            return;
                        } else {
                            goodsInfoList.clear();
                            goodsInfoList.addAll(response);
                            for (int i = 0; i < sqlData.size(); i++) {
                                long id = sqlData.get(i).getGoodsId();
                                int num = sqlData.get(i).getNum();
                                for (int j = 0; j < goodsInfoList.size(); j++) {
                                    if (id == goodsInfoList.get(j).getGoodsId()) {
                                        goodsInfoList.get(j).setNum(num);
                                    }
                                }
                            }
                            newGoodsAdapter.notifyData(goodsInfoList);
                        }
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        super.onError(code, errorMessage);
                        Logger.e("获取商品列表失败:" + code + "," + errorMessage);
                    }

                    @Override
                    public Class<GoodsInfo> getType() {
                        return GoodsInfo.class;
                    }
                }
        );
    }

    @Override
    public void onBackClick() {
        goodsDaoUtil.deleteAll();
        super.onBackClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //15分钟后回到主界面
        AppBaseActivity.TIMER_TIME = 15 * 60 * 1000;
    }

    @Override
    public void onBackPressed() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
            mComplexBgDimView.setVisibility(View.GONE);
            rlCartIcon.setBackgroundResource(R.drawable.shape_circle);
            return;
        }
        goodsDaoUtil.deleteAll();
        super.onBackPressed();
    }
}
